<?php
/**
 *
 * ============================================================================
 * * 版权所有 度拉拉 * *
 * 网站地址: http://www.dlltrip.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author By: 倪宗锋
 * PhpStorm AliLogin.php
 * Create By 2017/6/8 10:47 $
 */

namespace common\service\login;

use common\models\ShUserSystemAuth;
use common\service\pay\AliPay;
use common\util\CurlInterface;
use common\util\Util;

class AliLogin
{

    /**
     * Des:获取静默授权登录地址
     * Name: getLoginUrlUnAuth
     * @param $showUrl
     * @return string
     * @author 倪宗锋
     */
    public function getLoginUrlUnAuth($showUrl)
    {
        $PayConfig = Util::getAliPayConfig();
        $siteConfig = Util::getSiteConfig();
        $redirect_uri = $siteConfig['authLoginUrl'];
        $setLoginUrl = $siteConfig['host_name'] . $siteConfig['setLoginUrl'] . '&redirect=' . urlencode($showUrl);
        $urlObj["app_id"] = $PayConfig['app_id'];
        $urlObj["scope"] = "auth_base";//授权登录
        $urlObj["redirect_uri"] = $redirect_uri . '&redirect=' . urlencode($setLoginUrl);
        $bizString = http_build_query($urlObj);
        $url = $siteConfig['ali_authorizeUrl'] . $bizString;
        return $url;
    }

    /**
     * Function Description:根据code获取token
     * Function Name: getToken
     * @param $code
     *
     * @return array
     *
     * @author 倪宗锋
     */
    public function getToken($code)
    {
        $PayConfig = Util::getAliPayConfig();
        $siteConfig = Util::getSiteConfig();
        $param["app_id"] = $PayConfig['app_id'];
        $param["method"] = 'alipay.system.oauth.token';
        $param["charset"] = 'UTF-8';
        $param['sign_type'] = 'RSA';
        $param['timestamp'] = date('Y-m-d H:i:s');
        $param['version'] = '1.0';
        $param['grant_type'] = 'authorization_code';
        $param["code"] = $code;
        $param['sign'] = AliPay::getSign($param);
        $url = $siteConfig['ali_authTokenUrl'];
        $curlInterface = new CurlInterface($param, 4);
        $curlInterface->setBaseUrl($url);
        $getToken = $curlInterface->execute('', 'POST');
        if (empty($getToken['alipay_system_oauth_token_response']['user_id'])) {
            return Util::returnArrEr('参数无效！');
        }
        return Util::returnArrSu('', ['openid' => $getToken['alipay_system_oauth_token_response']]);
    }
}